package com.xingfei.blog.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.support.destination.BeanFactoryDestinationResolver;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Session;

/**
 * http://stackoverflow.com/questions/42356712/java-spring-jms-jmstemplate-to-ibm-mq
 * Created by yhang on 2017/5/7.
 */
@Configuration
public class ActiveMQFactory {

    @Value("${spring.activemq.broker-url}")
    private String brokerurl;

    @Value("${spring.activemq.user}")
    private String user;

    @Value("${spring.activemq.password}")
    private String password;

    @Autowired
    private BeanFactory springContextBeanFactory;

    @Bean(name = "connectionFactory")
    public ConnectionFactory connectionFactory() {

        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory();
        try {
            factory.setBrokerURL(brokerurl);
            factory.setUserName(user);
            factory.setPassword(password);
            //factory.setClientID("client1");
            factory.setTrustAllPackages(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return factory;
    }

    @Bean(name = "cachingConnectionFactory")
    public CachingConnectionFactory cachingConnectionFactory(){
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setSessionCacheSize(50);
        factory.setTargetConnectionFactory(connectionFactory());
        factory.setReconnectOnException(true);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public Connection queueSession(ConnectionFactory connectionFactory) throws JMSException {
        return connectionFactory.createConnection();
    }

//    @Bean(name = "jmsListenerContainerFactory" )
//    public DefaultJmsListenerContainerFactory containerFactory(ConnectionFactory connectionFactory) {
//        DefaultJmsListenerContainerFactory factory =
//                new DefaultJmsListenerContainerFactory();
//        factory.setConnectionFactory(connectionFactory);
//        factory.setDestinationResolver(new BeanFactoryDestinationResolver(springContextBeanFactory));
//        factory.setConcurrency("3-10");
//        return factory;
//    }

}